const CommonApi = require('../../../api/common.js');
const commonUtil = require('../../../utils/common.js');

Page({
  data: {
    _userInfo: null,
  },

  onLoad(options) {},
  onReady() {},
  onShow() {
    let userInfo = wx.getStorageSync('userInfo');
    this.setData({_userInfo: userInfo})
  },
  onHide() {},
  onUnload() {},
  getUserProfile() {
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res);
        wx.login({
          success: (loginRes) => {
            console.log(loginRes);
            this.xcxLogin(loginRes.code)
          },
        })
      }
    })
  },
  xcxLogin(code){
    let that = this;
    CommonApi.bindXcxWeiXin({code: code}).then(res=>{
      console.log(res);
      if (res.retCode == "000000" && res.errCode == "000000") {
        wx.showToast({icon: 'success', title: "绑定成功"})
        commonUtil.getLoginUser()
        setTimeout(()=>{
          let userInfo = wx.getStorageSync('userInfo');
          that.setData({_userInfo: userInfo})
        }, 200)
      } else {
        wx.showToast({icon: 'error', title: res.errMsg,})
      }
    })
  },
  bindXcxWeiXin(){
    this.getUserProfile();
  },
  unbindWeiXin(){
    let that = this;
    CommonApi.unbindWeiXin().then(res=>{
      if (res.retCode == '000000' && res.errCode == '000000') {
        wx.showToast({icon: 'success', title: "解绑成功"})
        commonUtil.getLoginUser()
        setTimeout(()=>{
          let userInfo = wx.getStorageSync('userInfo');
          that.setData({_userInfo: userInfo})
        }, 1000)
      }
    })
  },
  confirmClick(){
    if (this.data._userInfo.bindWeiXin) {
      this.unbindWeiXin()
    } else {
      this.bindXcxWeiXin();
    }
  },
  goBack(){
    wx.navigateBack({delta: 1});
  },
  
  onPullDownRefresh() {},
  onReachBottom() {},
  onShareAppMessage() {}
})